package com.deceen.common.config;

import com.deceen.common.filters.JwtAuthenticationFilter;
import com.deceen.common.filters.PasswordLoginFilter;
import com.deceen.common.filters.PhoneLoginFilter;
import com.deceen.common.security.*;
import com.deceen.common.utils.RedisClientUtil;
import com.deceen.demo.dao.UserMapper;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.annotation.Resource;

/**
 * @author: zzx
 * @date: 2018/10/15 16:47
 * @description:
 */
@Configuration
public class SpringSecurityConf extends WebSecurityConfigurerAdapter {


    @Resource
    AjaxAuthenticationEntryPoint authenticationEntryPoint;//未登陆时返回 JSON 格式的数据给前端（否则为 html）
    @Resource
    AjaxAuthenticationSuccessHandler authenticationSuccessHandler; //登录成功返回的 JSON 格式数据给前端（否则为 html）
    @Resource
    AjaxAuthenticationFailureHandler authenticationFailureHandler; //登录失败返回的 JSON 格式数据给前端（否则为 html）
    @Resource
    AjaxLogoutSuccessHandler logoutSuccessHandler;//注销成功返回的 JSON 格式数据给前端（否则为 登录时的 html）
    @Resource
    AjaxAccessDeniedHandler accessDeniedHandler;//无权访问返回的 JSON 格式数据给前端（否则为 403 html 页面）
    @Resource
    JwtAuthenticationFilter jwtAuthenticationTokenFilter; // JWT 拦截器
    @Resource
    UserMapper userMapper;
    @Resource
    PasswordEncoder passwordEncoder;
    @Resource
    RedisClientUtil redisClientUtil;

//    @Override
//    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//        // 加入自定义的安全认证
////        auth.authenticationProvider(provider);
//        auth.userDetailsService(userDetailsService).passwordEncoder(new BCryptPasswordEncoder());
//    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        // 去掉 CSRF
        http.csrf().disable()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) // 使用 JWT，关闭token
                .and()

                .httpBasic().authenticationEntryPoint(authenticationEntryPoint)

                .and()
                .authorizeRequests()//定义哪些URL需要被保护、哪些不需要被保护
                .antMatchers("/test/register").permitAll() //允许匿名注册
                .anyRequest()//任何请求,登录后可以访问
                .access("@rbacauthorityservice.hasPermission(request,authentication)") // RBAC 动态 url 认证

//                .and()
//                .formLogin()  //开启登录, 定义当需要用户登录时候，转到的登录页面
////                .loginPage("/test/login.html")
////                .loginProcessingUrl("/login")
//                .successHandler(authenticationSuccessHandler) // 登录成功
//                .failureHandler(authenticationFailureHandler) // 登录失败
//                .permitAll()

                .and()
                .logout()//默认注销行为为logout
                .logoutUrl("/logout")
                .logoutSuccessHandler(logoutSuccessHandler)
                .permitAll()
        ;
//
//        // 记住我
//        http.rememberMe().rememberMeParameter("remember-me")
//                .userDetailsService(userDetailsService).tokenValiditySeconds(1000);

        http.exceptionHandling().accessDeniedHandler(accessDeniedHandler); // 无权访问 JSON 格式的数据
        http.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class); // JWT Filter
        http.addFilterAt(customJSONLoginFilter(), UsernamePasswordAuthenticationFilter.class); // JWT Filter
        http.addFilterAt(phoneLoginFilter(), UsernamePasswordAuthenticationFilter.class); // JWT Filter

    }

    /**
     * 自定义认证过滤器
     */
    private PasswordLoginFilter customJSONLoginFilter() {
        PasswordLoginFilter customJSONLoginFilter = new PasswordLoginFilter("/login",userMapper, passwordEncoder,redisClientUtil);
        customJSONLoginFilter.setAuthenticationFailureHandler(authenticationFailureHandler);
        customJSONLoginFilter.setAuthenticationSuccessHandler(authenticationSuccessHandler);
        return customJSONLoginFilter;
    }

    private PhoneLoginFilter phoneLoginFilter(){
        PhoneLoginFilter phoneLoginFilter = new PhoneLoginFilter("/phone",userMapper,redisClientUtil);
        phoneLoginFilter.setAuthenticationFailureHandler(authenticationFailureHandler);
        phoneLoginFilter.setAuthenticationSuccessHandler(authenticationSuccessHandler);
        return phoneLoginFilter;
    }

}